package com.sharefang.aproject.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;


import com.sharefang.aproject.R;
import com.sharefang.aproject.constant.CacheKey;
import com.sharefang.aproject.utils.CacheHelper;
import com.sharefang.aproject.utils.CheckUtil;


/**
 * 启动
 *
 * @author Lei 2016年7月26日10:46:49
 */

public class LoadingActivity extends Activity implements CacheKey {
    private Context tag = LoadingActivity.this;
    private static final String Tag = LoadingActivity.class.getSimpleName();
    private static final long SHOW_TIME_MIN = 1500;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置为全屏模式
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_loading);

        //检查更新
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                long startTime = System.currentTimeMillis();
                checkUpdate();
                long loadingTime = System.currentTimeMillis() - startTime;
                if (loadingTime < SHOW_TIME_MIN) {
                    try {
                        Thread.sleep(SHOW_TIME_MIN - loadingTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                transferActivity();
            }
        }.execute(new Void[]{});
    }

    /**
     * 跳转Activity
     */
    private void transferActivity() {
        Intent intent = new Intent();
        if (isFirstRun()) {
            //第一次运行
            CacheHelper.put(FIRST_RUN,"false");
            intent.setClass(tag, GuideActivity.class);
        } else if (isLogined()) {
            intent.setClass(tag, MainActivity.class);
        } else {
            intent.setClass(tag, LoginActivity.class);
        }
        startActivity(intent);

        LoadingActivity.this.finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 检查更新
     */
    private void checkUpdate() {

    }

    /**
     * 检查是否已登录
     *
     * @return
     */
    private boolean isLogined() {
        return CheckUtil.isLogined();
    }

    /**
     * 是否第一次运行
     *
     * @return
     */
    private boolean isFirstRun() {
        return CheckUtil.isFirstRun();
    }
}
